package com.boot.cluster.utils;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.HessianInput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/***
 * Hessian2 序列化由于Hessian
 */
public class HessianSerializer {

    public static <T> T deserialize(byte[] array) {
        HessianInput hessianInput = null;
        try (ByteArrayInputStream is = new ByteArrayInputStream(array)) {
            // Hessian的反序列化读取对象
            Hessian2Input input = new Hessian2Input(is);
            T t = (T) input.readObject();
            input.close();
            return t;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> byte[] serialize(T object) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream();
        ) {
            Hessian2Output output = new Hessian2Output(os);
            // Hessian的序列化输出
            output.writeObject(object);
            output.flush();
            output.close();
            return os.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}